class Api::V1::DecisionsController < Api::V1::BaseController
	before_action :set_decision, only: [:show, :edit, :update, :destroy]
	before_action :find_project_or_group, only: [:index]

	def index
		if params[:project_id]
			@decisions = @project.decisions
		elsif params[:group_id]
			@decisions = @group.decisions
		else
			@decisions = Decision.all
		end
	end

	def create
		@decision = Decision.new(decision_params)
		if @decision.save
			render action: "show"
		else
			render :status => 406,
					:json => {
						:status_code => 406,
						:message => "Error creating resource!",
						:content => @decision.errors.full_messages
					}
		end
	end

	def show
	end

	def update
		if @decision.update(decision_params)
			render :status => 200,
					:json => { 
						:status_code => 200,
						:message => "Resource updated succesfully!",
						:content => ""
					 }
		else
			render :status => 406, 
					:json => {
						:status_code => 406,
						:message => "Error updating resource!"
						:content => @decision.errors.full_messages
					 }
		end
	end

	def destroy
		if @decision.destroy
			render :status => 200,
					:json => { 
						:status_code => 200,
						:message => "Resource deleted succesfully!",
						:content => ""
					}
		else
			render :status => 406, 
					:json => {
						:status_code => 406,
						:message => "Error deleting resource!",
						:content => @decision.errors.full_messages
					}
		end
	end

	private

		def set_decision
     		@decision = Decision.find(params[:id])
     		rescue ActiveRecord::RecordNotFound
				error = "The resource that you were looking for could not be found."
				render :status => 404, 
						:json => { 
							:status_code => 404,
							:message => error,
							:content => ""
						 }
   		end

   		def find_project_or_group
			if params[:project_id]
				@project = Project.find(params[:project_id])
			elsif params[:group_id]
				@group = Group.find(params[:group_id])
			end
			rescue ActiveRecord::RecordNotFound
				error = "The resource that you were looking for could not be found."
				render :status => 404, 
						:json => { 
							:status_code => 404,
							:message => error,
							:content => ""
						 }
		end

		def decision_params
			params.require(:decision).permit(:name, :group_id, :project_id)
		end
end